import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;

/**
 * <pre>
 * Created with IntelliJ IDEA.
 * User: zhengzhi
 * Date: 2017/9/11
 * Time: 16:44
 * To change this template use File | Settings | File Templates.
 * </pre>
 *
 * @author Administrator
 *
 * 使用ThreadFactory来创建自己的Thread。工厂模式来创建自己的Thread。
 * 在创建线程的同时，记录线程创建的个数，并记录每个线程创建的时间等信息。
 */
public class MyThreadFactory implements ThreadFactory{

    private int counter;
    private String name;
    private List<String> stats;


    //构造函数
    public MyThreadFactory(String name) {
        counter = 0;
        this.name = name;
        stats = new ArrayList<String>();
    }


    /**
     * 实现接口中唯一的方法：newThread
     */
    @Override
    public Thread newThread(Runnable r) {

        //创建一个线程
        Thread thread = new Thread(r,name + "-Thread-" + counter);
        counter++;
        stats.add(String.format("Created thread %d with name %s on%s \n",thread.getId(),thread.getName(),new Date()));
        return thread;
    }

    public String getStas(){
        StringBuffer stringBuffer = new StringBuffer();
        Iterator<String> iterator = stats.iterator();
        
        while (iterator.hasNext()){
            stringBuffer.append(iterator.next());
        }
        return stringBuffer.toString();
    }


    public static void main(String[] args) {
        MyThreadFactory factory = new MyThreadFactory("MyThreadFactory");

        ATask task = new ATask();
        Thread thread = null;
        for(int i = 0; i < 10; i++) {

            /**
             * 创建一个线程
             */
            thread = factory.newThread(task);
            thread.start();
        }
        System.out.printf("Factory stats:\n");
        System.out.printf("%s\n",factory.getStas());
    }

    }


    class ATask implements Runnable{

        @Override
        public void run() {
            try {
                Thread.sleep(1000000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}
